#include <muduo/net/TcpServer.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/Buffer.h>
#include <iostream>
#include <string>
#include <unordered_map>

class DictServer
{
public:
    DictServer(int port)
        : _server(&_loop, muduo::net::InetAddress("0.0.0.0", port), "DictServer",
                  muduo::net::TcpServer::kNoReusePort)
    {
        //注册函数
        _server.setConnectionCallback(std::bind(&DictServer::OnConnection
        ,this,std::placeholders::_1));

        _server.setMessageCallback(std::bind(&DictServer::OnMessage,this,
        std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));
    }
    void start()
    {
        _server.start();
        _loop.loop();
    }

private:
    // 设置回调函数
    //1.连接管理
    void OnConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if(conn->connected())
        {
            std::cout<< "连接成功" <<std::endl;
        }
        else
        {
            std::cout<< "连接断开"<<std::endl;
        }
    }
    //2.信息管理
    void OnMessage(const muduo::net::TcpConnectionPtr &conn,
        muduo::net::Buffer * buf,muduo::Timestamp)
    {
        static std::unordered_map<std::string,std::string> dicts = {
                {"hello",  "你好"},
                {"world",  "世界"},
                {"see",  "看"}
            };;
        //调用数据
        std::string msg = buf->retrieveAllAsString();
        std::string res ;
        auto pos = dicts.find(msg);
        if(pos != dicts.end())
        {
            res = pos->second;
        }
        else
        {
            res = "未知单词";
        }
        conn->send(res);
    }

private:
    muduo::net::EventLoop _loop;   // 设置事件循环
    muduo::net::TcpServer _server; // 开启服务器
};

int main()
{
    DictServer svr(8888);
    svr.start();
    return 0;
}
